//
//  UserTask.m
//  XNet
//
//  Created by easystudio on 6/27/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "UserTask.h"


@implementation UserTask

@synthesize _sTaskType;

-(id) InitWithType:(NSString*)type Delegate:(NSObject *)delegate
{
    self = [super init];
    _sTaskType = type;
    _oDelegate = (NSObject<UserTaskDelegate> *)delegate;
    _oThread = nil;
    return self;
}
-(void) setDelegate:(NSObject <UserTaskDelegate>*) delegate
{
    _oDelegate = delegate;
}
-(void) cancel
{
    [_oThread cancel];
}

-(void) Excute
{
    if(!_oThread)
    {
        _oThread = [[NSThread alloc] initWithTarget:self selector:@selector(DoInBackground) object:nil];
    }
    else
    {
        if ([_oThread isExecuting]) 
        {
            return;
        }
        else
        {
            [_oThread release];
            _oThread = [[NSThread alloc] initWithTarget:self selector:@selector(DoInBackground) object:nil];
            
        }
    }
    [_oDelegate OnPreExcute];
    [_oThread start];
}

-(void) DoInBackground
{
//    NSAutoreleasePool* pool = [[[NSAutoreleasePool alloc] init] autorelease];
    [_oDelegate DoInBackground];
    [self performSelectorOnMainThread:@selector(OnPostExcute) withObject:nil  waitUntilDone:YES];
//    [pool release];
}

-(void) OnPostExcute
{
    [_oDelegate OnPostExcute];
}

-(void) dealloc
{
    [super dealloc];
    [_oThread release];
}

-(BOOL) isRunning
{
    return ![_oThread isFinished];
}
//-(void) DoInBackground

@end
